/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package org.kota105.xml;

import java.io.DataOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import org.kota105.ui.generic.Layout;
import org.kota105.ui.generic.Widget;

/**
 *
 * @author pikpun
 */
public class XMLGenerator {

    private StringBuilder stringBuilder;

    public XMLGenerator() {
    }

    public void generateXml(Layout layout, File file) throws FileNotFoundException, IOException {
        stringBuilder = new StringBuilder();
        stringBuilder.append("<?xml version=\"1.0\" encoding=\"utf-8\"?>").append("\n");
        generateWidget(layout, 1);
        System.out.println(stringBuilder.toString());
        writeToFile(file);
    }

    private void generateWidget(Widget widget, int tabNumber) {
        System.out.println("tabNumber for = " + widget.getXMLName() + " = " + tabNumber);
        writeToBuilder("<" + widget.getXMLName(), tabNumber - 1);
        //for add xmlns:android="http://schemas.android.com/apk/res/android"
        if (widget instanceof Layout) {
            if (((Layout) widget).isRoot()) {
                writeToBuilder("xmlns:android=\"http://schemas.android.com/apk/res/android\"", tabNumber);
            }
        }
        for (int i = 0; i < widget.getProperties().size(); i++) {
            writeToBuilder(widget.getProperties().get(i).getXmlName()
                    + " = \""
                    + widget.getProperties().get(i).getValue()
                    + "\"",
                    tabNumber, (i == (widget.getProperties().size() - 1)));
        }
        writeToBuilder(">", 0);
        if (widget instanceof Layout) {
            tabNumber++;
            for (Widget wt : ((Layout) widget).getWidgets()) {
                generateWidget(wt, tabNumber);
            }
            writeToBuilder("</"
                    + widget.getXMLName()
                    + ">", tabNumber - 2);
        } else {
            writeToBuilder("</"
                    + widget.getXMLName()
                    + ">", tabNumber - 1);
        }
    }

    private void writeToBuilder(String value, int tab) {
        writeToBuilder(value, tab, false);
    }

    private void writeToBuilder(String value, int tab, boolean needEnter) {
        for (int i = 0; i < tab; i++) {
            stringBuilder.append("\t");
        }
        stringBuilder.append(value).append(needEnter ? "" : "\n");
    }

    private void writeToFile(File file) throws FileNotFoundException, IOException {
        FileOutputStream fos = new FileOutputStream(file);
        DataOutputStream dos = new DataOutputStream(fos);
        dos.write((stringBuilder.toString().getBytes()));
    }
}
